package com.fanrui.code.util.core;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class JsonUtil<JAVEBEAN> {
	
	Class<JAVEBEAN> clazz;

	public JsonUtil(Class<JAVEBEAN> clazz) {
		this.clazz = clazz;
	}

	public JsonArray listToJsonArray(List<JAVEBEAN> list) {
		JsonArray array = new JsonArray();
		if(list != null){
			Gson gson = new Gson();
			for(JAVEBEAN javebean:list){
				array.add(gson.toJsonTree(javebean));
			}
		}
		return array;
	}

	/**
	 * json字符串转List集合
	 */

	public List<JAVEBEAN> jsonToList(String json) {
		List<JAVEBEAN> lst = new ArrayList<JAVEBEAN>();
		JsonArray array = new JsonParser().parse(json).getAsJsonArray();
		for (final JsonElement elem : array) {
			lst.add(new Gson().fromJson(elem, clazz));
		}
		return lst;
	}

	public static String getRandomElementByJsonArray(String jsonArray){
		try{
			JsonArray ja = new JsonParser().parse(jsonArray).getAsJsonArray();
			if(ja != null && ja.size() > 0){
				int random = RandomUtils.nextInt(0, ja.size());
				return ja.get(random).toString().substring(1, ja.get(random).toString().length() - 1);
			}
		}catch(Exception e){
			return "";
		}
		return "";
		
	}
	
	public static String getRandomElementByJsonArray(List<String> list){
		try{
			if(list != null && !list.isEmpty()){
				int random = RandomUtils.nextInt(0, list.size());
				return list.get(random);
			}
		}catch(Exception e){
			return "";
		}
		return "";
		
	}

}
